<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商品详情页</title>
</head>
<body>
    <h1>商品详情页</h1>
    <div>
        <p>商品名称：<span id="name"></span></p>
        <p>商品价格：<span id="price"></span></p>
        <button id="buyButton" onclick="buyNow()" disabled>立即抢购</button>
    </div>

<script th:src="@{/js/jquery-3.6.0.js}"></script>
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/common.js}"></script>

<script>
    const code = "1000";
    let token = "";
    let timestamp = "";

    $(document).ready(queryProduct);

    function queryProduct() {
        const url = API["productData"];
        const params =  {code: code};
        get(url, params, function(result) {
            if (result.code == RESULT_OK) {
                const data = result.data;
                $("#name").text(data.name);
                $("#price").text((data.price/100).toFixed(2));

                if (data.tag == "秒杀商品") {
                    queryActivity(code);
                }
            }
        });
    }

    function queryActivity(code) {
        const url = API["activityData"];
        const params = {code: code};
        get(url, params, function (result, headers) {
            const data = result.data;
            $("#price").text((data.price/100).toFixed(2));
            if (data.stock > 0) {
                $("#buyButton").removeAttr("disabled");
            }

            token = headers["token"];
            timestamp = headers["timestamp"];
        });
    }

    function buyNow() {
        const url = PAGE["settlement"];
        const params = {code: code, token: token, timestamp: timestamp};
        redirect(url, params)
    }

</script>
</body>
</html>